package com.cheyun.netsalev3.view

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.Editable
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.bean.CarBrandParam
import com.cheyun.netsalev3.databinding.ActivityRegisterBinding
import com.cheyun.netsalev3.databinding.ActivityUserFaceBinding
import com.cheyun.netsalev3.databinding.ActivityUserSettingBinding
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.utils.api.ApiStores
import com.cheyun.netsalev3.viewmodel.RegisterActivityViewModel
import com.cheyun.netsalev3.viewmodel.UserFaceActivityViewModel
import com.cheyun.netsalev3.viewmodel.UserSettingActivityViewModel
import com.cheyunkeji.er.utils.ToastUtil
import com.jeremyliao.liveeventbus.LiveEventBus
import java.io.File

class UserFaceActivity : BaseActivity<ActivityUserFaceBinding>() {
    private val PERMISSION_CAMERA_REQUEST_CODE = 0x00000012
    private val PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 0x00000013
    private val PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE2 = 0x00000014

    private var photoUri: Uri? = null
    private var picPath: String? = null
    private val fileUri = File(Environment.getExternalStorageDirectory().path + "/photo.jpg")
    private var mCameraUri: Uri? = null   //用于保存拍照图片的uri
    private var mid: Int = 0
    var activity:Activity? = null
    private var imageStr = ""

    override fun initContentView(): Int {
        return R.layout.activity_user_face
    }

    override fun initViewModel(): ViewModel? {
        return ViewModelProviders.of(this).get(UserFaceActivityViewModel::class.java)
    }

    override fun initData() {
        mid = MySharedPreferences.getLoginData()?.member?.uid!!

        binding.viewModel?.headimg?.observe(this, Observer {
            Glide.with(this)
                    .load(it)
                    .transform(GlideRoundTransform(this, 5))
                    .placeholder(R.drawable.datuchicun)
                    .error(R.drawable.datuchicun)
                    .into(binding?.ivHead!!)
        })
        binding.txtChoosePhoto.setOnClickListener{
            val hasCameraPermission = ContextCompat.checkSelfPermission(it.context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
            if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) {
                //调起相册。
                gotoPhoto()
            } else {
                //没有权限，申请权限。
                ActivityCompat.requestPermissions(this,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE
                )
            }
        }
        binding.txtChooseCarema.setOnClickListener {
            if (
                    ContextCompat.checkSelfPermission(
                            it.context,
                            Manifest.permission.CAMERA) !== PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(
                            it.context,
                            Manifest.permission.READ_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(
                            it.context,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {

                //没有权限，申请权限。
                ActivityCompat.requestPermissions(
                        this,
                        arrayOf(Manifest.permission.CAMERA,
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE),
                        PERMISSION_CAMERA_REQUEST_CODE)
            } else {
                //有调起相机拍照。
                gotoCarema()
            }
        }

    }

    override fun initView() {
        activity = this

        LiveEventBus.get()
                .with("uploadOrderImg", String::class.java)
                .observe(this, Observer {
                    if (!TextUtils.isEmpty(it)) {
                        imageStr = it
                        setImages()
                    }
                })
    }

    fun setImages(){
        Glide.with(this).load(Uri.parse(imageStr)).transform(GlideRoundTransform(this, 5)).into(binding.ivHead)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            doPhoto(requestCode, data)
        }
    }

    private fun gotoCarema() {
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        if (ContextCompat.checkSelfPermission(activity!!,
                        Manifest.permission.CAMERA) !== PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(activity!!,
                        Manifest.permission.READ_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(activity!!,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this.activity!!, Manifest.permission.CAMERA)) {
                ToastUtil.toastLongMessage("您已经拒绝过一次")
            }
            ActivityCompat.requestPermissions(this.activity!!, arrayOf(Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE2)
        } else {//有权限直接调用系统相机拍照
            if (hasSdcard()) {
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
                    photoUri = Uri.fromFile(fileUri)
                } else {
                    photoUri = FileProvider.getUriForFile(activity!!, this.activity!!.getPackageName() + ".provider", fileUri)
                }
//                PhotoUtils.takePicture(this.activity, photoUri, 1)
                if (photoUri != null) {
                    captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                    startActivityForResult(captureIntent, 1)
                }
            } else {
                ToastUtil.toastLongMessage("您没有存储卡")
            }
        }
    }

    fun gotoPhoto() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        startActivityForResult(Intent.createChooser(intent, "请选择图片"), 2)
    }

    fun hasSdcard(): Boolean {
        val state = Environment.getExternalStorageState()
        return state == Environment.MEDIA_MOUNTED
    }

    private fun doPhoto(requestCode: Int, data: Intent?) {
        if (requestCode == 1) {
            try {
                picPath = UriUtils.getTakePhotoPath(data);
                var impageUpload = ImageUploader();
                impageUpload.ossImg(activity!!,picPath);
            } catch (e: Exception) {
                e.printStackTrace()
            }

        } else if (requestCode == 2) {
            if (data == null) {
                ToastUtils.showLong("选择图片文件出错")
                return
            }
            photoUri = data.data
            if (photoUri == null) {
                ToastUtils.showLong("选择图片文件出错")
                return
            }
            if (ContextCompat.checkSelfPermission(this.activity!!,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this.activity!!,
                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 2
                )
            } else {
                picPath = UriUtils.getRealPathFromUriAboveApi19(activity, photoUri)
            }

            if(CommonFunc.isPic(picPath)){
                var impageUpload = ImageUploader();
                impageUpload.ossImg(activity!!,picPath);
            }else{
                Toast.makeText(activity, "选择图片文件不正确", Toast.LENGTH_LONG).show()
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE -> {
                //调用系统相机申请拍照权限回调
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (hasSdcard()) {
                        gotoPhoto()
                    } else {
                        ToastUtils.showLong("您没有存储卡")
                    }
                } else {
                    ToastUtils.showLong("请允许使用存储空间")
                }
            }
            2 -> {
                //调用系统相册申请Sdcard权限回调
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    gotoPhoto()
                } else {
                    ToastUtils.showLong("请允许使用存储空间")
                }
            }
            PERMISSION_CAMERA_REQUEST_CODE -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //允许权限，有调起相机拍照。
                    gotoCarema()
                } else {
                    //拒绝权限，弹出提示框。
                    ToastUtils.showLong("请允许使用相机权限")
                }
            }
            PERMISSION_WRITE_EXTERNAL_STORAGE_REQUEST_CODE2 -> {
                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //允许权限，有调起相机拍照。
                    gotoCarema()
                } else {
                    //拒绝权限，弹出提示框。
                    ToastUtils.showLong("请允许使用存储空间")
                }
            }
        }
    }

}
